<?php
/*
 * @Author: your name
 * @Date: 2020-12-04 10:33:04
 * @LastEditTime: 2021-01-14 16:18:49
 * @LastEditors: Please set LastEditors
 * @Description: 数据库自增id相关操作
 * @FilePath: /special/application/common/database/AutoIncreMentService.php
 */
namespace app\common\database;

use app\common\exception\CustomException;
use think\Db;

class AutoIncreMentService
{
    //锁位置
    private static $lock_path = 'mysql_auto_increase.lock';

    /**
     * @name: 获取指定表自增id
     * @Param: 
     * @Description: 
     * @Author: foo
     * @Date: 2020-12-04 10:34:21
     */
    public static function getTableAutoId(string $table, int $increase_number = 0)
    {
        //打开一个文件
        $flp = fopen(self::$lock_path, 'w+');
        //文件加锁
        flock($flp, LOCK_EX);
        $sql = "SELECT AUTO_INCREMENT FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = '" . config('database.prefix') . "$table' limit 1;";
        $Max = Db::query($sql);
        
        if (empty($Max))
        {
            throw new CustomException('数据库或表不存在!', 302);
        }
        
        $return = $Max[0]['AUTO_INCREMENT'];
        if ($increase_number > 0)
        {
            $auto_increment_number = $return + $increase_number;
            Db::execute('ALTER TABLE ' . config('database.prefix') . $table . ' AUTO_INCREMENT=' . $auto_increment_number);
        }
        //文件解锁
        flock($flp, LOCK_UN);
        //释放文件
        fclose($flp);
        
        return $return;
    }
}